package com.castle.fortress.admin.rule.rule.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.rule.rule.dto.ImportDto;
import com.castle.fortress.admin.rule.rule.entity.RuleEntity;
import com.castle.fortress.admin.rule.rule.dto.RuleDto;
import com.castle.fortress.admin.rule.rule.service.RuleService;
import com.castle.fortress.admin.utils.Sequence;
import com.castle.fortress.common.utils.ConvertUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.admin.core.annotation.CastleLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.castle.fortress.admin.utils.ExcelUtils;
import javax.servlet.http.HttpServletResponse;
import com.castle.fortress.common.entity.DynamicExcelEntity;

import java.util.*;
import java.lang.NumberFormatException;

/**
 * 规则表 控制器
 *
 * @author
 * @since 2025-04-21
 */
@Api(tags="规则表管理控制器")
@Controller
public class RuleController {
	@Autowired
	private RuleService ruleService;

	/**
	 * 规则表的分页展示
	 * @param ruleDto 规则表实体类
	 * @param current 当前页
	 * @param size  每页记录数
	 * @return
	 */
    @CastleLog(operLocation="规则表",operType = OperationTypeEnum.QUERY)
	@ApiOperation("规则表分页展示")
	@GetMapping("/rule/page")
	@ResponseBody
	@RequiresPermissions("rule:rule:rule:pageList")
	public RespBody<IPage<RuleDto>> pageRule(RuleDto ruleDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
		Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
		Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
		Page<RuleDto> page = new Page(pageIndex, pageSize);
			IPage<RuleDto> pages = ruleService.pageRule(page, ruleDto);

		return RespBody.data(pages);
	}

	/**
	 * 规则表的列表展示
	 * @param ruleDto 规则表实体类
	 * @return
	 */
    @CastleLog(operLocation="规则表",operType = OperationTypeEnum.QUERY)
	@ApiOperation("规则表列表展示")
	@GetMapping("/rule/list")
	@ResponseBody
	public RespBody<List<RuleDto>> listRule(RuleDto ruleDto){
		List<RuleDto> list = ruleService.listRule(ruleDto);
		return RespBody.data(list);
	}

	/**
	 * 规则表保存
	 * @param ruleDto 规则表实体类
	 * @return
	 */
    @CastleLog(operLocation="规则表",operType = OperationTypeEnum.INSERT)
	@ApiOperation("规则表保存")
	@PostMapping("/rule/save")
	@ResponseBody
	@RequiresPermissions("rule:rule:rule:save")
	public RespBody<Object> saveRule(@RequestBody RuleDto ruleDto){
		if(ruleDto == null ){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
          RuleEntity ruleEntity = ConvertUtil.transformObj(ruleDto,RuleEntity.class);
		  ruleEntity.setId(Sequence.getInstance().nextId());
		if(ruleService.save(ruleEntity)){
			return RespBody.data(ruleEntity);
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * 规则表编辑
	 * @param ruleDto 规则表实体类
	 * @return
	 */
    @CastleLog(operLocation="规则表",operType = OperationTypeEnum.UPDATE)
	@ApiOperation("规则表编辑")
	@PostMapping("/rule/edit")
	@ResponseBody
	@RequiresPermissions("rule:rule:rule:edit")
	public RespBody<String> updateRule(@RequestBody RuleDto ruleDto){
		if(ruleDto == null || ruleDto.getId() == null || ruleDto.getId().equals(0L)){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
          RuleEntity ruleEntity = ConvertUtil.transformObj(ruleDto,RuleEntity.class);
		if(ruleService.updateById(ruleEntity)){
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * 规则表删除
	 * @param id
	 * @return
	 */
    @CastleLog(operLocation="规则表",operType = OperationTypeEnum.DELETE)
	@ApiOperation("规则表删除")
	@PostMapping("/rule/delete")
	@ResponseBody
	@RequiresPermissions("rule:rule:rule:delete")
	public RespBody<String> deleteRule(@RequestParam Long id){
		if(id == null ){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		if(ruleService.removeById(id)) {
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}


	/**
	 * 规则表批量删除
	 * @param ids
	 * @return
	 */
    @CastleLog(operLocation="规则表",operType = OperationTypeEnum.DELETE)
	@ApiOperation("规则表批量删除")
	@PostMapping("/rule/deleteBatch")
	@ResponseBody
	@RequiresPermissions("rule:rule:rule:deleteBatch")
	public RespBody<String> deleteRuleBatch(@RequestBody List<Long> ids){
		if(ids == null || ids.size()<1){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		if(ruleService.removeByIds(ids)) {
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * 规则表详情
	 * @param id 规则表id
	 * @return
	 */
    @CastleLog(operLocation="规则表",operType = OperationTypeEnum.QUERY)
	@ApiOperation("规则表详情")
	@GetMapping("/rule/info")
	@ResponseBody
	@RequiresPermissions("rule:rule:rule:info")
	public RespBody<RuleDto> infoRule(@RequestParam Long id){
		if(id == null){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
        RuleDto ruleDto =  ruleService.getByIdExtends(id);
		return RespBody.data(ruleDto);
	}

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation="规则表",operType = OperationTypeEnum.EXPORT)
	@PostMapping("/rule/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<RuleDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<RuleDto> list = ruleService.listRule(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}

	/**
	 * 批量导入规则
	 * @return
	 */
	@CastleLog(operLocation="规则表",operType = OperationTypeEnum.INSERT)
	@ApiOperation("批量导入规则")
	@PostMapping("/rule/batchImport")
	@ResponseBody
	@RequiresPermissions("rule:rule:rule:save")
	public RespBody<String> batchImportRules(@RequestBody ImportDto importDto){
		if(importDto.getRuleList() == null || importDto.getRuleList().isEmpty()){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		if (Objects.isNull(importDto.getScenarioId())) {
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}

		Long scenarioId = importDto.getScenarioId();

		List<RuleEntity> entityList = new ArrayList<>(importDto.getRuleList().size());
		// 转换JSON数据为实体
		for (Map<String, Object> ruleMap : importDto.getRuleList()) {
			RuleEntity ruleEntity = new RuleEntity();
			ruleEntity.setId(Sequence.getInstance().nextId());
			ruleEntity.setScenarioId(scenarioId);
			// 设置规则基本信息
			if (ruleMap.containsKey("ruleName")) {
				ruleEntity.setRuleName(String.valueOf(ruleMap.get("ruleName")));
			}
			if (ruleMap.containsKey("ruleDesc")) {
				ruleEntity.setRuleDesc(String.valueOf(ruleMap.get("ruleDesc")));
			}
			if (ruleMap.containsKey("ruleType")) {
				ruleEntity.setRuleType(ruleMap.get("ruleType") != null ? String.valueOf(ruleMap.get("ruleType")) : null);
			}
			if (ruleMap.containsKey("ruleSource")) {
				ruleEntity.setRuleSource(String.valueOf(ruleMap.get("ruleSource")));
			}
			if (ruleMap.containsKey("riskLevel")) {
				ruleEntity.setRiskLevel(String.valueOf(ruleMap.get("riskLevel")));
			}
			if (ruleMap.containsKey("message")) {
				ruleEntity.setMessage(ruleMap.get("message") != null ? String.valueOf(ruleMap.get("message")) : null);
			}

			// 设置当前时间作为创建/更新时间
			ruleEntity.setCreateTime(new Date());
			ruleEntity.setUpdateTime(new Date());

			// 默认未删除状态
			ruleEntity.setIsDeleted(2);

			entityList.add(ruleEntity);
		}

		// 批量保存规则
		if(ruleService.saveBatch(entityList)){
			return RespBody.data("批量导入成功，共导入" + entityList.size() + "条规则");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * 批量修改规则分组
	 * @param ids 规则ID列表
	 * @param scenarioId 目标场景ID
	 * @return
	 */
	@CastleLog(operLocation="规则表",operType = OperationTypeEnum.UPDATE)
	@ApiOperation("批量修改规则分组")
	@PostMapping("/rule/updateGroup")
	@ResponseBody
	@RequiresPermissions("rule:rule:rule:edit")
	public RespBody<String> updateRuleGroup(@RequestBody List<Long> ids, @RequestParam Long scenarioId) {
		if (ids == null || ids.isEmpty()) {
			throw new BizException(GlobalRespCode.PARAM_MISSED, "规则ID列表不能为空");
		}

		if (scenarioId == null) {
			throw new BizException(GlobalRespCode.PARAM_MISSED, "目标场景ID不能为空");
		}

		boolean result = ruleService.updateRuleGroup(ids, scenarioId);

		if (result) {
			return RespBody.data("已成功将" + ids.size() + "条规则移动到新分组");
		} else {
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

}
